package security;

import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.Arrays;

import javax.crypto.SecretKey;

public class SymmetricKeyTest {
	public static void main(String[] args) {
	    try {
			KeyStore ks = KeyStore.getInstance("JCEKS");
			
//			java.io.FileInputStream fis = new java.io.FileInputStream("chat_3");
			ks.load(null, "123456".toCharArray());
//			fis.close();
		    
			String msg = "Hello World";
			SymmetricKeyEncryptor enc = SymmetricKeyEncryptor.getInstance();
			SecretKey key = Generator.getInstance().generateSymmetricKey(
					"123456".getBytes());
			
			System.out.println("Before = " + Arrays.toString(key.getEncoded()));
			enc.saveSymmetricKey(ks, "ahmed", key);
			SecretKey key2 = enc.loadSymmetricKey(ks, "ahmed");
			System.out.println("After = " + Arrays.toString(key2.getEncoded()));
			
			key = Generator.getInstance().generateSymmetricKey(
					"7891011".getBytes());
			System.out.println("Before = " + Arrays.toString(key.getEncoded()));
			enc.saveSymmetricKey(ks, "mohamed", key);
			SecretKey key3 = enc.loadSymmetricKey(ks, "mohamed");
			System.out.println("After = " + Arrays.toString(key3.getEncoded()));
			
			key = Generator.getInstance().generateSymmetricKey(
					"9786854".getBytes());
			System.out.println("Before = " + Arrays.toString(key.getEncoded()));
			enc.saveSymmetricKey(ks, "server", key);
			SecretKey key4 = enc.loadSymmetricKey(ks, "server");
			System.out.println("After = " + Arrays.toString(key4.getEncoded()));
			
			java.io.FileOutputStream fos = new java.io.FileOutputStream("chat_3");
			ks.store(fos, "123456".toCharArray());
			fos.close();
			
			byte[] encrypted = enc.encrypt(msg.getBytes(), key);
			String cipher = new String(encrypted);
			System.out.println("Encrypted = " + cipher);
			byte[] arr = enc.decrypt(encrypted, key);
			String decrypted = new String(arr);
			System.out.println("Decrypted = " + decrypted);
	    } catch (KeyStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CertificateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
